﻿using System;
using System.Linq;
using FluentValidation;
using LINQPad.OpenAccess.Data;

namespace LINQPad.OpenAccess.UI.ViewModel.Validators
{
    /// <summary>
    /// Validator for <see cref="PredefinedConnectionSettingsViewModel"/>
    /// </summary>
    public class PredefinedConnectionSettingsViewModelValidator : ConnectionSettingsViewModelValidator<PredefinedConnectionSettingsViewModel>
    {
        private static Func<PredefinedConnectionData, bool> NotBeEmpty( Func<PredefinedConnectionData, string> propertySelector )
        {
            return e => !String.IsNullOrWhiteSpace( propertySelector( e ) );
        }
        private static Func<PredefinedConnectionSettingsViewModel, PredefinedConnectionData, bool> BeEqual( Func<PredefinedConnectionSettingsViewModel, string> propertySelector, Func<PredefinedConnectionData, string> otherPropertySelector )
        {
            return ( p, e ) => String.Equals( propertySelector( p ), otherPropertySelector( e ) );
        }
        //private static bool ContainAtLeastOnePredefinedConnection( PredefinedConnectionData[] predefinedConnections )
        //{
        //    return predefinedConnections != null && predefinedConnections.Length > 0;
        //}

        /// <summary>
        /// Initializes a new instance of the <see cref="PredefinedConnectionSettingsViewModelValidator" /> class.
        /// </summary>
        public PredefinedConnectionSettingsViewModelValidator( )
        {
            //this.RuleFor( p => p.PredefinedConnections )
            //    .Must( ContainAtLeastOnePredefinedConnection )
            //    .WithMessage( "no predefined connections available !" );

            this.RuleFor( p => p.PredefinedConnection )
                .NotNull( )
                .WithMessage( "no predefined connection set !" );

            this.RuleFor( p => p.PredefinedConnection )
                .Must( NotBeEmpty( e => e.ConnectionString ) )
                .WithMessage( "connection string not set !" )
                .Must( NotBeEmpty( e => e.Name ) )
                .WithMessage( "connection name not set !" )
                .Must( BeEqual( p => p.ProviderName, e => e.ProviderName ) )
                .WithMessage( "provider mismatch !" )
                .When( e => e.PredefinedConnection != null );
        }
    }
}
